<template>
  <!-- <s-layout title="班级" tabbar="/pages/index/class" navbar="inner" :bgStyle="template.page"
    :navbarStyle="template.navigationBar" onShareAppMessage> -->
  <!-- <s-layout title="班级" tabbar="/pages/index/class" navbar="custom" :bgStyle="template.page"> -->
  <s-layout title="班级" class="set-userinfo-wrap" :bgStyle="{ color: '#fff' }">
    <!-- <view class="top-banner" v-if="topBannerList.length">
      <swiper class="home-swiper" circular="true" interval="3000" indicator-dots="true" autoplay
        indicator-active-color="#FF6000" indicator-color="#fff">
        <swiper-item class="swiper-item" v-for="(item,index) in topBannerList" :key="index"
          @click="toBannerDetail(item.url)">
          <image lazy-load :src="item.picUrl" mode="aspectFill"></image>
        </swiper-item>
      </swiper>
    </view> -->
    <view v-if="classList.length" class="list ss-p-x-16 ss-p-t-20 ss-p-b-80">
      <view class="list-item ss-p-b-20" v-for="item in classList" :key="item.id">
        <view class="img-box">
          <image :src="sheep.$url.cdn(item.logo)" mode="aspectFill" />
          <view :class="['status', getStatusInfo(item.status).class]">{{ getStatusInfo(item.status).text }}</view>
          <view class="tag" v-if="item.courseTypeName">{{item.courseTypeName}}</view>
        </view>
        <view class="item-card ss-p-y-20 ss-p-x-20">
          <view class="time-tab ss-flex">
            <view class="txt ss-flex-col ss-col-top">
              <view>本周</view>
              <view>课表</view>
            </view>
            <view class="tab-box ss-flex ss-row-between ss-flex-1" v-if="weekList.length">
              <view class="group ss-flex ss-row-center ss-flex-col ss-flex-1" v-for="(i,index) in weekList"
                :key="index">
                <text class="date">{{i.date}}</text>
                <text class="date rad" :class="{'act': item.dayList?.includes(i.i)}">{{i.day}}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="detail ss-p-x-10 ss-p-b-10">
          <view class="title ss-line-1 ss-p-y-10">{{item.name}}</view>
          <view class="info ss-flex ss-row-between">
            <view class="ss-flex">
              <view class="ss-flex">
                <image class="head-img"
                  :src=" item.ownerAvatar ? sheep.$url.cdn(item.ownerAvatar) : 'https://txtdev-1252097407.cos.ap-guangzhou.myqcloud.com/static/img/shop/default_avatar.png'"
                  mode="aspectFill" />
                <text class="name ss-m-l-10">{{item.ownerName}}</text>
              </view>
              <text class="ss-m-l-10 address">{{item.storeName}}</text>
            </view>
            <button class="ss-reset-button btn"
              @tap.stop="sheep.$router.go(`/pages/classes/detail?id=${item.id}`)">查看班级</button>
          </view>
        </view>
      </view>
    </view>
    <s-empty v-else-if="classList.length === 0 && noData" text="班级空空如也,快去加入班级吧~" />
  </s-layout>
</template>

<script setup>
  import sheep from '@/sheep';
  import {
    onLoad,
    onShow,
    onPageScroll,
    onPullDownRefresh
  } from '@dcloudio/uni-app';
  import {
    computed,
    ref,
    reactive,
    watch
  } from 'vue';
  import {
    showAuthModal
  } from '@/sheep/hooks/useModal';

  // 隐藏原生tabBar
  uni.hideTabBar();


  const template = computed(() => sheep.$store('app').template.home);
  import ClassApi from '@/sheep/api/member/class';
  import ArticleApi from '@/sheep/api/promotion/article';
  const isLogin = computed(() => sheep.$store('user').isLogin);
  // 监听 isLogin 的变化
  watch(isLogin, (newVal, oldVal) => {
    if (newVal) {
      // console.log('用户已登录');
      loadPage()
    } else {
      // console.log('用户已退出登录');

    }
  })
  const sys_navBar = sheep.$platform.navbar;
  const topBannerList = reactive([])
  let classList = reactive([])
  let weekList = reactive([])
  let noData = ref(false)
  const page = reactive({
    pageSize: 99,
    pageNo: 1
  })
  // 获取轮播图
  const getBannerList = () => {
    ArticleApi.getBanner({
      position: 7
    }).then(res => {
      if (res.code == 0) {
        topBannerList.splice(0, topBannerList.length)
        topBannerList.push(...res.data)
      } else {
        uni.showToast({
          icon: 'none',
          title: res.msg,
        });
      }
    })
  }
  // 根据状态返回对应的 class
  const getStatusInfo = (status) => {
    const statusMap = {
      0: {
        class: 'status-waiting',
        text: '正常'
      },
      1: {
        class: 'status-enrolling',
        text: '停课'
      },
      2: {
        class: 'status-ended',
        text: '结班'
      }
    }
    // 如果状态未定义，返回默认值
    return statusMap[status] || {
      class: '',
      text: '未知'
    }
  }

  //获取当前周日期
  const getCurrentWeek = () => {
    let list = []
    const today = new Date()
    const currentDayOfWeek = today.getDay() // 0（周日）- 6（周六）
    const startOfWeek = new Date(today) // 从今天开始计算
    startOfWeek.setDate(today.getDate() - currentDayOfWeek + 1) // 周一

    for (let i = 0; i < 7; i++) {
      const date = new Date(startOfWeek)
      date.setDate(startOfWeek.getDate() + i)
      const dayOfWeek = ['一', '二', '三', '四', '五', '六', '日'][i]

      // 格式化为 MM/DD
      const formattedDate =
        `${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')}`

      list.push({
        date: formattedDate, // 格式化为 MM/DD
        day: dayOfWeek,
        i: i + 1
      });
    }
    return list
  }

  const loadPage = () => {
    ClassApi.getClassList(page).then(res => {
      noData.value = true
      if (page.pageNo === 1) {
        classList.splice(0, classList.length); // 清空数组
      }
      if (res.code == 0) {
        classList.push(...res.data.list)
      } else {
        uni.showToast({
          icon: 'none',
          title: res.msg,
        })
      }

    })
  }


  onShow(() => {
    // getBannerList()
    if (!isLogin.value) {
      showAuthModal()
      return
    }
    loadPage()
    weekList = Object.assign(weekList, getCurrentWeek())
  })

  // 下拉刷新
  onPullDownRefresh(() => {
    sheep.$store('app').init();
    setTimeout(function() {
      uni.stopPullDownRefresh();
    }, 800);
  });

  onPageScroll(() => {});
</script>

<style lang="scss" scoped>
  .top-banner {
    height: 312rpx;
    width: 100vw;

    .home-swiper {
      width: 100%;
      height: 100%;
      margin: 0 auto;
      font-size: 0;
      overflow: hidden;

      .swiper-item image {
        width: 100%;
        height: 100%;
      }
    }
  }

  .list {
    background: #fff;

    .list-item {

      .img-box {
        font-size: 0;
        position: relative;
        height: 360rpx;
        width: 100%;


        image {
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: 16rpx 16rpx 0 0;
        }

        .status {
          left: 0;

          &.status-error {
            color: #e6a23c;
          }

          &.status-end {
            color: #409eff;
          }

          &.status-warning {
            color: #f56c6c;
          }
        }

        .tag {
          right: 0;
        }

        .tag,
        .status {
          position: absolute;
          bottom: 0;
          padding: 10rpx 20rpx;
          background-color: rgba(0, 0, 0, 0.6);
          color: #fff;
          font-size: 28rpx;
        }
      }

      .time-tab {
        // border: 1px solid #000;
        text-align: center;

        .txt {
          width: 14%;
          border-right: 1px solid #e9e9e9;
          letter-spacing: 8rpx;
        }

        .tab-box {
          padding-left: 10rpx;

          .group {
            font-size: 20rpx;

            .date {
              height: 40rpx;
              line-height: 40rpx;
            }

            .rad {
              width: 40rpx;
            }

            .act {
              background: #FF6000;
              color: #fff;
              border-radius: 50%;
            }
          }
        }
      }

      .detail {

        .title {
          font-size: 28rpx;
          font-weight: bold;
          line-height: 48rpx;
        }

        .info {
          .head-img {
            width: 40rpx;
            height: 40rpx;
            border-radius: 50%;
          }

          .address {
            color: #999;
            font-size: 26rpx;
          }

          .btn {
            background: linear-gradient(to right, #FF6000, #FE832A);
            height: 50rpx;
            line-height: 50rpx;
            padding: 0 20rpx;
            border-radius: 25rpx;
            font-size: 24rpx;
            color: #fff;
          }
        }
      }
    }
  }
</style>